package com.ruoyi.qif.service.impl;

import java.time.YearMonth;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.qif.mapper.QifRepairMapper;
import com.ruoyi.qif.domain.QifRepair;
import com.ruoyi.qif.service.IQifRepairService;
import com.ruoyi.common.core.text.Convert;

/**
 * 锜风公寓-维修Service业务层处理
 *
 * @author David
 * @date 2025-11-03
 */
@Service
public class QifRepairServiceImpl implements IQifRepairService {
    @Autowired
    private QifRepairMapper qifRepairMapper;

    /**
     * 查询锜风公寓-维修
     *
     * @param repairId 锜风公寓-维修主键
     * @return 锜风公寓-维修
     */
    @Override
    public QifRepair selectQifRepairByRepairId(Long repairId) {
        return qifRepairMapper.selectQifRepairByRepairId(repairId);
    }

    /**
     * 查询锜风公寓-维修列表
     *
     * @param qifRepair 锜风公寓-维修
     * @return 锜风公寓-维修
     */
    @Override
    public List<QifRepair> selectQifRepairList(QifRepair qifRepair) {
        // 初始化参数Map（若依推荐用params存储额外条件）
        if (qifRepair.getParams() == null) {
            qifRepair.setParams(new HashMap<>(2));
        }
        // 获取当前年月（默认查询条件）
        Calendar cal = Calendar.getInstance();
        int year = qifRepair.getQueryYear() != null ? qifRepair.getQueryYear() : cal.get(Calendar.YEAR);
        int month = qifRepair.getQueryMonth() != null ? qifRepair.getQueryMonth() : (cal.get(Calendar.MONTH) + 1); // 月份+1（Calendar月份从0开始）

        // 2. 生成字符串格式的起止日期（yyyy-MM-dd）
        String startDateStr = String.format("%d-%02d-01", year, month); // 当月1日（如2025-10-01）
        // 计算当月最后一天（处理2月、大月小月）
        YearMonth yearMonth = YearMonth.of(year, month);
        int lastDay = yearMonth.lengthOfMonth();
        String endDateStr = String.format("%d-%02d-%02d", year, month, lastDay); // 当月最后一天（如2025-10-31）

        // 3. 存入params（字符串类型）
        qifRepair.getParams().put("qifRepairDateStart", startDateStr);
        qifRepair.getParams().put("qifRepairDateEnd", endDateStr);
        return qifRepairMapper.selectQifRepairList(qifRepair);
    }

    /**
     * 新增锜风公寓-维修
     *
     * @param qifRepair 锜风公寓-维修
     * @return 结果
     */
    @Override
    public int insertQifRepair(QifRepair qifRepair) {
        qifRepair.setCreateTime(DateUtils.getNowDate());
        return qifRepairMapper.insertQifRepair(qifRepair);
    }

    /**
     * 修改锜风公寓-维修
     *
     * @param qifRepair 锜风公寓-维修
     * @return 结果
     */
    @Override
    public int updateQifRepair(QifRepair qifRepair) {
        qifRepair.setUpdateTime(DateUtils.getNowDate());
        return qifRepairMapper.updateQifRepair(qifRepair);
    }

    /**
     * 批量删除锜风公寓-维修
     *
     * @param repairIds 需要删除的锜风公寓-维修主键
     * @return 结果
     */
    @Override
    public int deleteQifRepairByRepairIds(String repairIds) {
        return qifRepairMapper.deleteQifRepairByRepairIds(Convert.toStrArray(repairIds));
    }

    /**
     * 删除锜风公寓-维修信息
     *
     * @param repairId 锜风公寓-维修主键
     * @return 结果
     */
    @Override
    public int deleteQifRepairByRepairId(Long repairId) {
        return qifRepairMapper.deleteQifRepairByRepairId(repairId);
    }

    @Override
    public String importQifExpenditure(List<QifRepair> qifRepairList, boolean updateSupport) {
        if (StringUtils.isNull(qifRepairList) || qifRepairList.isEmpty()) {
            throw new IllegalArgumentException("导入数据不能为空");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String operName = ShiroUtils.getLoginName();
        for (QifRepair qifRepair : qifRepairList) {
            try {
                // 这里可以根据实际业务添加数据验证逻辑，比如判断某些必填字段是否为空等
                if (StringUtils.isBlank(qifRepair.getRoomNum())) {
                    throw new Exception("房间号不能为空");
                }
                QifRepair existingRepair = qifRepairMapper.selectQifRepairByUniqueKey(qifRepair.getRoomNum(), qifRepair.getRemark());
                if (StringUtils.isNull(existingRepair)) {
                    qifRepair.setCreateBy(operName);
                    qifRepair.setCreateTime(DateUtils.getNowDate());
                    qifRepairMapper.insertQifRepair(qifRepair);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、导入成功");
                } else if (updateSupport) {
                    qifRepair.setUpdateBy(operName);
                    qifRepair.setUpdateTime(DateUtils.getNowDate());
                    qifRepairMapper.updateQifRepair(qifRepair);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、数据已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、房间号 " + qifRepair.getRoomNum() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很遗憾，导入失败 " + failureNum + " 条数据：");
            throw new RuntimeException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条。");
        }
        return successMsg.toString();
    }

    @Override
    public int changeStatus(QifRepair repair) {
        repair.setUpdateBy(ShiroUtils.getLoginName());
        repair.setUpdateTime(DateUtils.getNowDate());
        return qifRepairMapper.updateQifRepair(repair);
    }
}
